package com.bawan.vims.common.helper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p> Title        : FileHelper.java </p>
 * <p> Description	: FileHelper.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: JOCHEN ZHENG </p>
 * <p> Create		: 2015-1-5 11:31:52 </p> 
 * <p> version 		: 1.0 </p>
 */
public class FileHelper {
	protected static final Logger logger = LoggerFactory.getLogger(FileHelper.class);

	/**
	 * 解压zip文件
	 * 
	 * @param zipFileName
	 *            zip文件全路径
	 * @param outputDirectory
	 */
	@SuppressWarnings("unused")
	public static void unZip(String zipFileName, String outputDirectory) {
		ZipInputStream zipIs = null;
		ZipEntry zipEty = null;
		int fileCount = 0;

		try {
			zipIs = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));
			if (zipIs == null) {
				logger.error("unZip: create ZipInputStream failed!");
				return;
			}
		} catch (Exception e) {
			logger.error("unZip: create ZipInputStream failed!", e);
		}

		logger.info("unZip: begin...");
		do {
			BufferedOutputStream bos = null;

			try {
				zipEty = zipIs.getNextEntry();
				if (zipEty == null)
					break;

				logger.info("unZip: be unzipping file=" + zipEty.getName());

				if (zipEty.isDirectory()) {
					// 压缩包内不存在目录，如果是目录，跳过
					logger.info("unZip: don't unzip dir=" + zipEty.getName());
					continue;
				}

				String filename = outputDirectory + File.separator + zipEty.getName();
				logger.info("unZip: unzip file=" + zipEty.getName() + " to \"" + filename + "\"");

				File fl = new File(filename);
				if (fl.exists())
					fl.delete();// 删除临时目录下的同名文件

				bos = new BufferedOutputStream(new FileOutputStream(fl));
				int size;
				while ((size = zipIs.read()) != -1) {
					bos.write(size);
					bos.flush();
				}

				fileCount++;
			} catch (Exception e) {
				logger.error("unZip: unzip file=" + zipEty.getName() + " failed!", e);
			} finally {
				try {
					if (bos != null)
						bos.close();
				} catch (Exception e) {
					logger.error("unZip: close bos failed!", e);
				}
			}
		} while (true);
		try {
			if (zipIs != null)
				zipIs.close();
		} catch (Exception e) {
			logger.error("unZip: close zipIs failed!", e);
		}

		logger.info("unZip: finish success unzip[" + fileCount + "] files.");
	}

	/**
	 * 文件COPY操作
	 * 
	 * @param srcFile
	 * @param trgFile
	 * @return
	 * @throws Exception
	 */
	public static boolean copyFile(String srcFile, String trgFile) {
		boolean result = true;
		File srcFileObj = new File(srcFile);
		File trgFileObj = new File(trgFile);
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(srcFileObj);
			fos = new FileOutputStream(trgFileObj);
			byte buff[] = new byte[128 * 1024]; // BUFFER要适中,否则速度也不见得明显,这个值是一个经验值
			int buffCount = 0;
			while ((buffCount = fis.read(buff)) != -1) {
				fos.write(buff, 0, buffCount);
			}
		} catch (Exception e) {
			result = false;
			logger.error("copy file '" + srcFile + "' to '" + trgFile + "' 异常！", e);
		} finally {
			try {
				if (fos != null)
					fos.close();
				if (fis != null)
					fis.close();
			} catch (Exception e) {
				logger.error("copyFile() 关闭输入/输出流异常！", e);
			}
		}

		return result;
	}

	/**
	 * 格式化路径
	 * 
	 * @param filepath
	 * @return
	 */
	public static String formatFilePath(String filepath) {
		String path = filepath.replace("\\", "/");
		if (!path.endsWith("/")) {
			path += "/";
		}
		return path;
	}
}
